import {getStore, setStore} from "@/util/store";
import {getDictList} from "@/api/dict";
import {validatenull} from "@/util/validate";

const dicts = {
  state: {
    dicDataList: getStore({name: 'dictionary'}) || {},
  },
  actions: {
    GetDicData({state,commit}, code) {
      return new Promise((resolve, reject) => {
        if (validatenull(state.dicDataList[code])) {
          getDictList(code).then(res => {
            const data = res.data.data;
            commit('SET_DICTIONARY', {code, data});
          });
        }
        resolve();
      });
    }
  },
  mutations: {
    SET_DICTIONARY: (state, {code, data}) => {
      let dicData = [];
      data.forEach(dicItem => {
        dicData.push({
          label: dicItem.dictValue,
          value: dicItem.dictKey
        })
      })
      state.dicDataList[code] = dicData;
      setStore({name: 'dictionary', content: state.dicDataList, type: 'session'})
    }
  }
}

export default dicts;
